import {onMounted, ref} from "vue";
import {onBeforeRouteUpdate, useRoute, useRouter} from "vue-router";
import service from "../../service/service.js";

export default function SearchCon() {
    const route = useRoute()
    const router = useRouter()
    let searchContent = ref('')
    let ArticleList = ref([])
    let pattern = /[`~!@#_$%^&*()=|{}'',\\\[\\\].<>/?~！@#￥……&*（）——|{}‘；”“'。、\s]/g
    onMounted(() => {
        searchContent.value = route.query.content
        service.searchArticle({content: route.query.content}).then(r => {
            let data = r.data['msg']
            for (let i = 0; i < data.length; i++) {
                let tmpObj = {}
                let content = data[i]['Content'].substring(0, 100)
                content = content.replace(pattern, '')
                tmpObj.id = data[i]['ID']
                tmpObj.title = data[i]['Title']
                tmpObj.sort = data[i]['Class']
                tmpObj.content = content
                tmpObj.author = data[i]['Author']
                ArticleList.value.push(tmpObj)
            }
        })
    })
    onBeforeRouteUpdate((to) => {
        // 获取第一页文章
        service.searchArticle({content: to.query.content}).then(r => {
            searchContent.value = to.query.content
            ArticleList.value = []
            let data = r.data['msg']
            if (r.data.code === 200) {
                for (let i = 0; i < data.length; i++) {
                    let tmpObj = {}
                    let content = data[i]['Content'].substring(0, 100)
                    content = content.replace(pattern, '')
                    tmpObj.id = data[i]['ID']
                    tmpObj.title = data[i]['Title']
                    tmpObj.sort = data[i]['Class']
                    tmpObj.content = content
                    tmpObj.author = data[i]['Author']
                    ArticleList.value.push(tmpObj)
                }
            }
        })
    })
    const toArticleBtn = (id) => {
        router.push({
            path: '/article_details',
            query: {
                id: id
            }
        })
    }
    return {
        searchContent,
        ArticleList,
        toArticleBtn,
    }
}